<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, watch } from "vue";
import request from "../../utils/request";
import { ElNotification } from "element-plus";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
const fileList = ref([]);
const upload = ref(null);

// 移除图片
const handledel = (file) => {
  fileList.value = fileList.value.filter((i) => {
    return i.uid !== file.uid;
  });
};
//展示大图
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

//限制大小
//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changeUploadImg = (file) => {
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  if (!isJPG && !isPNG) {
    ElNotification.error("上传图片只能是 JPG 或者 PNG 格式!");
    // 取消时在文件列表中删除该文件
    upload.value.handleRemove(file);
    return isJPG || isPNG;
  } else if (file.size / 1024 / 1024 > 4) {
    ElNotification.error("单张图片大小不能超过4MB!");
    return false;
  } else {
    fileList.value.push(file);
  }
};

let breadList = []; // 路由集合
const route = useRoute();
const getBreadcrumb = (url) => {
  let matched = url.matched;
  //如果不是首页
  if ("Home" == matched[0].name) {
    matched[0].meta = { title: "系统首页" };
  }
  breadList = matched;
};
watch(
  route,
  (newValue, oldValue) => {
    // console.log(222222,newValue)
    getBreadcrumb(newValue);
  },
  { deep: true, immediate: true }
);

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    const formData = new FormData();
    fileList.value.forEach((value, index) => {
      formData.append("file", value.raw);
    });
    formData.append("jzName", ruleForm.jzName);
    formData.append("salary", ruleForm.salary);
    formData.append("phonenumber", ruleForm.phonenumber);
    formData.append("content", ruleForm.content);
    formData.append("place", ruleForm.place);
    formData.append("grade", ruleForm.grade);
    formData.append("star", ruleForm.star);
    formData.append("category", ruleForm.category);
    if (valid) {
      // console.log("提交更新", fields);
      request
        .post("/jzxx/add", formData, {
          headers: {
            "Content-Type":
              "multipart/form-data;charset=UTF-8; boundary=<calculated when request is sent>",
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            formEl.resetFields(); //清除表单
            ElNotification({
              title: "添加成功",
              message: "成功添加岗位信息",
            });
          } else {
            ElNotification({
              title: "添加失败",
              message: "请检查失败原因",
            });
          }
        })
        .catch((e) => {
          ElNotification({
            title: "添加失败",
            message: "请检查失败原因",
          });
        });
    } else {
      ElNotification({
        title: "校验失败",
        message: "请重新填写信息",
      });
    }
  });
};
const ruleForm = reactive({
  jzName: "",
  salary: "",
  phonenumber: "",
  content: "",
  category: "",
  place: "",
  // jzImg: "",
  grade: "",
  star: 1,
});
const rules = reactive({
  jzName: [
    {
      required: true,
      message: "请输入岗位名称",
      trigger: "blur",
    },
  ],
  salary: [
    {
      required: true,
      message: "请输入薪资",
      trigger: "blur",
    },
  ],
  phonenumber: [
    {
      required: true,
      message: "请输入联系电话",
      trigger: "blur",
    },
  ],
  content: [
    {
      required: true,
      message: "请输入介绍",
      trigger: "blur",
    },
  ],
  place: [
    {
      required: true,
      message: "请输入地址",
      trigger: "blur",
    },
  ],
  category: [
    {
      required: true,
      message: "请选择岗位类型",
      trigger: "change",
    },
  ],
  grade: [
    {
      required: true,
      message: "请输入招聘方信誉等级",
      trigger: "blur",
    },
  ],
  star: [
    {
      required: true,
      message: "请输入评分",
      trigger: "blur",
    },
  ],
});
const ruleFormRef = ref();

let categoryData = reactive([]);
//获取分类数据
const getCategory = () => {
  request
    .request({
      url: "/category/getAllCategory",
      method: "get",
    })
    .then((res) => {
      //获取数据
      res.data.data.forEach((e) => {
        categoryData.push(e);
      });
    })
    .catch((e) => {
      console.log(e);
    });
};
getCategory();
</script>

<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
          >{{ item.meta.title }}</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="container">
      <div>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          status-icon
        >
          <el-form-item label="岗位名" prop="jzName">
            <el-input v-model="ruleForm.jzName" />
          </el-form-item>
          <el-form-item label="薪资" prop="salary">
            <el-input v-model="ruleForm.salary" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phonenumber">
            <el-input v-model="ruleForm.phonenumber" />
          </el-form-item>
          <el-form-item label="介绍" prop="content">
            <el-input v-model="ruleForm.content" />
          </el-form-item>
          <el-form-item label="地址" prop="place">
            <el-input v-model="ruleForm.place" />
          </el-form-item>
          <el-form-item label="岗位类型" prop="category">
            <el-select
              v-model="ruleForm.category"
              placeholder="选择岗位分类"
              class="handle-select mr10"
            >
              <el-option
                v-for="(item, index) in categoryData"
                :key="index"
                :label="item.catName"
                :value="item.catId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="招聘方信誉等级">
            <el-select
              v-model="ruleForm.grade"
              class="m-2"
              placeholder="请选择等级"
            >
              <el-option key="0" value="A" />
              <el-option key="1" value="B" />
              <el-option key="2" value="C" />
              <el-option key="3" value="D" />
              <el-option key="4" value="暂无" />
            </el-select>
          </el-form-item>
          <el-form-item label="岗位评分" prop="star">
            <el-input type="number" max="5" min="1" v-model="ruleForm.star" />
          </el-form-item>
          <el-form-item label="岗位图片" prop="jzImg">
            <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-remove="handledel"
              :on-change="changeUploadImg"
              ref="upload"
              :file-list="fileList"
              :multiple="true"
              name="file"
              v-model="fileList"
              :limit="3"
            >
              <el-icon><Plus /></el-icon>
              <template #file="{ file }">
                <div>
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <el-icon><zoom-in /></el-icon>
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handledel(file)"
                    >
                      <el-icon><Delete /></el-icon>
                    </span>
                  </span>
                </div>
              </template>
              <template #tip>
                <div class="el-upload__tip">
                  一次最多只能上传3张图片,且单张图片大小不能超过4MB
                </div>
              </template>
            </el-upload>
            <!--  放大的图片  -->
            <el-dialog v-model="dialogVisible" top="7vh">
              <img
                w-full
                :src="dialogImageUrl"
                alt="Preview Image"
                style="width: 100%; height: auto"
              />
            </el-dialog>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >新增</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
